package com.xzzz.irda.guardcat.client.alert;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.xzzz.irda.guardcat.core.pojo.Alert;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

/**
 * 【Client】警告测试
 *
 * @author xzzz
 */
@Slf4j
@RestController
@RequestMapping("/guardcat/client/alert")
public class AlertClientController {
    private static final String sendResourceName = "/guardcat/client/alert/send";

    static {
        initFlowRole();
    }

    private static void initFlowRole() {
        FlowRule rule = new FlowRule();
        rule.setResource(sendResourceName);
        rule.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_DEFAULT); // 快速失败
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);                     // 阈值类型,QPS/线程数
        rule.setCount(1);                                               // 阈值个数,漏桶每秒放行个数
        FlowRuleManager.loadRules(CollUtil.newArrayList(rule));			// 设置规则
    }

    /**
     * 发送测试警告
     *
     * @param onlyProd 是否只发送生成环境
     * @param alert    警告信息
     * @return
     */
    @PostMapping("/send")
    public String send(@RequestParam boolean onlyProd, @RequestBody Alert alert) {
        Alert real = Alert.build(alert.getTitle(), alert.getContent(), alert.getNotification())
                .setLevel(Alert.Level.INFO)
                .setPhone(alert.getPhone())
                .setEmail(alert.getEmail())
                .setWechatRobot(alert.getWechatRobot());
        boolean result = AlertClientSender.send(real, onlyProd);
        if (result) {
            log.debug("[GUARDCAT] 测试警告发送成功");
            log.info("[GUARDCAT] 测试警告发送成功");
            log.warn("[GUARDCAT] 测试警告发送成功");
            log.error("[GUARDCAT] 测试警告发送成功");
        }
        return "success";
    }
}
